package com.hyt.it.ogt.ks.util;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * @author 刘恒活
 * @since 2021/6/28 14:46
 */
public class DateUtil extends org.apache.commons.lang3.time.DateUtils {

	private static String[] parsePatterns = { 
			"yyyy-MM-dd", 
			"yyyy-MM-dd HH:mm:ss", 
			"yyyy-MM-dd HH:mm", 
			"yyyy-MM", 
			"yyyy/MM/dd", 
			"yyyy/MM/dd HH:mm:ss", 
			"yyyy/MM/dd HH:mm", 
			"yyyy/MM", "yyyy.MM.dd",
			"yyyy.MM.dd HH:mm:ss", 
			"yyyy.MM.dd HH:mm", 
			"yyyy.MM" };

	/**
	 * 私有构造器
	 */
	private DateUtil() {

	}

	private static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

	public static long getSecondByNow() {
		return LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
	}

	public static String getNowStr() {
		return df.format(LocalDateTime.now());
	}

	public static String date2String(LocalDateTime time) {
		return df.format(time);
	}

	/**
	 * 获取当前时间前一小时的时间
	 * 
	 * @param date
	 * @return java.util.Date
	 */
	public static Date beforeOneHourToNowDate(Date date, int hours) {
		Calendar calendar = Calendar.getInstance();
		/* HOUR_OF_DAY 指示一天中的小时 */
		calendar.setTime(date);
		calendar.add(Calendar.HOUR_OF_DAY, hours);
		return calendar.getTime();
	}

	/**
	 * 日期型字符串转化为日期 格式 { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
	 * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy.MM.dd",
	 * "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
	 */
	public static Date parseDate(Object str) {
		if (str == null) {
			return null;
		}
		try {
			return parseDate(str.toString(), parsePatterns);
		} catch (ParseException e) {
			return null;
		}
	}
}
